import struct
import numpy as np
import matplotlib.pyplot as plt

def read_images(imgaes_path = 'data/test_images'):
    images_file = open(imgaes_path, 'rb')
    magic_number, images_num, rows, columns = struct.unpack('>4i', images_file.read(16))  #大端读取开头16个字节，内容分别为魔法数字、图片个数、图片的像素行数和列数
    images_num = int(images_num)
    rows = int(rows)
    columns = int(columns)
    images = np.fromfile(images_file, dtype=np.uint8).reshape(images_num, rows*columns)   #用np接收所有数据
    images_file.close()
    return images

def read_labels(labels_path = 'data/test_labels'):
    labels_file = open(labels_path, 'rb')
    magic_number, labels_num = struct.unpack('>2i', labels_file.read(8))  #大端读取开头8个字节，内容分别为魔法数字、标签个数
    labels_num = int(labels_num)
    labels = np.fromfile(labels_file, dtype=np.uint8) #用np接收所有数据
    labels_file.close()
    return labels
# print(read_image())

if __name__ == '__main__':
    divided_num = 6
    test_images = read_images('data/test_images')
    test_labels = read_labels('data/test_labels')
    train_images = read_images('data/train_images')
    train_labels = read_labels('data/train_labels')
    valid_images = train_images[:len(train_images)//divided_num]
    valid_labels = train_labels[:len(train_labels)//divided_num]
    train_images = train_images[len(train_images)//divided_num:]
    train_labels = train_labels[len(train_labels)//divided_num:]


    plt.imshow(train_images[88].reshape(28,28), cmap='gray')
    print(train_labels[88])
    plt.show()